import {
  ADD_TODO,
  UPDATE_TODO,
  DEL_TODO,
  CHECK_ALL,
  DEL_CHECKED,
} from "./constands";
const initState = {
  // list: [
  //   {
  //     todoName: "吃饭",
  //     isDone: true,
  //     id: 1,
  //   },
  //   {
  //     todoName: "睡觉",
  //     isDone: false,
  //     id: 2,
  //   },
  //   {
  //     todoName: "干活",
  //     isDone: true,
  //     id: 3,
  //   },
  // ],
  list:JSON.parse(localStorage.getItem('key'))||[]
};

export default function reducer(state = initState, action) {
  let newState,id;

  switch (action.type) {
    // 添加任务
    case ADD_TODO:
      const todoName = action.todoName;

      const todo = {
        todoName: todoName,
        isDone: false,
        id: Date.now(),
      };

      newState = [...state.list];
      console.log(newState);

      newState.push(todo);
      return {
        ...state,
        list: newState,
      };
    // 修改状态
    case UPDATE_TODO:
      id = action.id;

      newState = state.list.map((item) => {
        if (item.id === id) {
          item.isDone = !item.isDone;
        }
        return { ...item };
      });
      return {
        ...state,
        list: newState,
      };
    // 删除单个
    case DEL_TODO:
      id = action.id;

      newState = state.list.filter((item) => item.id !== id);

      return {
        ...state,
        list: newState,
      };
    // 全选
    case CHECK_ALL:
      const checked = action.checked;

      newState = state.list.map((item) => {
        item.isDone = checked;
        return { ...item };
      });
      return {
        ...state,
        list: newState,
      };
    //  删除已选
    case DEL_CHECKED:
      newState = state.list.filter((item) => {
        return !item.isDone;
      });
      return {
        ...state,
        list: newState,
      };

    default:
      return state;
  }
}
